package com.server.test.servlet.weixin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import net.arnx.jsonic.JSON;

import com.server.test.command.request.ReservationRequestBean;
import com.server.test.command.response.ReservationResponseBean;
import com.server.test.database.BaseDao;
import com.server.test.pojo.AccessToken;
import com.server.test.util.URL;
import com.server.test.util.WeixinUtil;


/**
 * 关注者预约 
 *
 */
public class OrderServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	private String readJsonFromRequestBody(HttpServletRequest request) throws IOException {
		StringBuffer jsonBuf = new StringBuffer();
		char[] buf = new char[2048];
		int len = -1;
		BufferedReader reader = request.getReader();
		while ((len = reader.read(buf)) != -1) {
			jsonBuf.append(new String(buf, 0, len));
		}
		return jsonBuf.toString();
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		
		// 处理中文问题
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String jsonStrRequest = readJsonFromRequestBody(request);
		
		System.out.println("请求的json数据 ： " + jsonStrRequest);

		ReservationRequestBean reservationRequestBean = new ReservationRequestBean();
		reservationRequestBean = JSON.decode(jsonStrRequest, ReservationRequestBean.class);
		System.out.println(reservationRequestBean.getTxtUser());
		
		ReservationResponseBean reservationResponseBean = new ReservationResponseBean();
		reservationResponseBean.setResultMessage("成功");
		reservationResponseBean.setStatus("0000");
		
		PrintWriter out = response.getWriter();
		out.write(JSON.encode(reservationResponseBean));
		out.flush();
		out.close();
		System.out.println("end");
		
		String sql = "insert into orderinfo (orderid, username, time, phone, customer,remark) VALUES (?,?, ?, ?, ?, ?)";
		BaseDao baseDao = new BaseDao();
		
		long orderid = System.currentTimeMillis();
		
		try {
			baseDao.executeInsert(sql, String.valueOf(orderid).substring(7),reservationRequestBean.getTxtUser(),reservationRequestBean.getTxtTime(),reservationRequestBean.getTxtPhone(),reservationRequestBean.getTxtCustomer(),reservationRequestBean.getTxtMemo());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

}
